//
//  HDLY_UploadAvatar.m
//  HDJinShaSiteMuseum
//
//  Created by liuyi on 2017/7/6.
//  Copyright © 2017年 HDNiuKuiming. All rights reserved.
//

#import "HDLY_UploadAvatar.h"

@interface HDLY_UploadAvatar ()<UINavigationControllerDelegate,UIImagePickerControllerDelegate>
{
    UIImagePickerController *pickerController;
}
@end

@implementation HDLY_UploadAvatar

- (instancetype)init {
    self = [super init];
    if (self) {
        declare = [HDDeclare sharedDeclare];
        [declare setLanguageType:kLanguage_Type_Chinese];
        //初始化pickerController
        pickerController = [[UIImagePickerController alloc]init];
        pickerController.view.backgroundColor =   [UIColor orangeColor];
        pickerController.delegate = self;
        pickerController.allowsEditing = YES;
    }
    return self;
}

- (void)chooseImgWithVC:(UIViewController *)vc {
    _currentVC = vc;
    [self editPortrait];
}

- (void)editPortrait {
    UIAlertController *VC = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];//设置为UIAlertControllerStyleActionSheet
    UIAlertAction *cameraAction = [UIAlertAction actionWithTitle:@"拍摄" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        //相机拍照
        if ([self isCameraAvailable] && [self doesCameraSupportTakingPhotos]) {
            pickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
            if ([self isFrontCameraAvailable]) {
                pickerController.cameraDevice = UIImagePickerControllerCameraDeviceFront;//设置默认为前置摄像头
            }
            NSMutableArray *mediaTypes = [[NSMutableArray alloc] init];
            [mediaTypes addObject:(__bridge NSString *)kUTTypeImage];
            pickerController.mediaTypes = mediaTypes;
            [_currentVC presentViewController:pickerController
                               animated:YES
                             completion:^(void){
                                 LOG(@"Picker View Controller is presented");
                             }];
        }
    }];
    UIAlertAction *albumAction = [UIAlertAction actionWithTitle:@"从手机相册选取" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        // 从相册中选取
        if ([self isPhotoLibraryAvailable]) {
            pickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            NSMutableArray *mediaTypes = [[NSMutableArray alloc] init];
            [mediaTypes addObject:(__bridge NSString *)kUTTypeImage];
            pickerController.mediaTypes = mediaTypes;
            [_currentVC presentViewController:pickerController
                               animated:YES
                             completion:^(void){
                                 LOG(@"Picker View Controller is presented");
                             }];
        }
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [cancelAction setValue:[UIColor darkGrayColor] forKey:@"titleTextColor"];
    [VC addAction:cameraAction];
    [VC addAction:albumAction];
    [VC addAction:cancelAction];
    [_currentVC presentViewController:VC animated:YES completion:NULL];
}

#pragma mark ---- UIImagePickerControllerDelegate -----
//完成照片的选取
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    /*
     UIImagePickerControllerMediaType; // an NSString UTTypeImage) *
     UIImagePickerControllerOriginalImage; // a UIImage 原始图片 *
     UIImagePickerControllerEditedImage; // a UIImage 裁剪后图片 *
     UIImagePickerControllerCropRect; // an NSValue (CGRect) *
     UIImagePickerControllerMediaURL; // an NSURL *
     UIImagePickerControllerReferenceURL
     */
    //NSLog(@"%s,info == %@",__func__,info);
    UIImage *userImage = [self fixOrientation:[info objectForKey:@"UIImagePickerControllerEditedImage"]];
    userImage = [self scaleImage:userImage toScale:0.3];
    //上传头像
    [self saveImage:userImage name:@"userImage"];
    if (self.successBlock) {
        self.successBlock(userImage);
    }
    [picker dismissViewControllerAnimated:YES completion:^(){
    }];
}

//取消照片选取
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:^(){
    }];
}

#pragma mark --- 对图片进行修剪处理 ----
//修正照片方向(手机转90度方向拍照)
- (UIImage *)fixOrientation:(UIImage *)aImage {
    // No-op if the orientation is already correct
    if (aImage.imageOrientation == UIImageOrientationUp)
        return aImage;
    // We need to calculate the proper transformation to make the image upright.
    // We do it in 2 steps: Rotate if Left/Right/Down, and then flip if Mirrored.
    CGAffineTransform transform = CGAffineTransformIdentity;
    switch (aImage.imageOrientation) {
        case UIImageOrientationDown:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, aImage.size.height);
            transform = CGAffineTransformRotate(transform, M_PI);
            break;
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformRotate(transform, M_PI_2);
            break;
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, 0, aImage.size.height);
            transform = CGAffineTransformRotate(transform, -M_PI_2);
            break;
        default:
            break;
    }
    switch (aImage.imageOrientation) {
        case UIImageOrientationUpMirrored:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.height, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
        default:
            break;
    }
    // Now we draw the underlying CGImage into a new context, applying the transform
    // calculated above.
    CGContextRef ctx = CGBitmapContextCreate(NULL, aImage.size.width, aImage.size.height,
                                             CGImageGetBitsPerComponent(aImage.CGImage), 0,
                                             CGImageGetColorSpace(aImage.CGImage),
                                             CGImageGetBitmapInfo(aImage.CGImage));
    CGContextConcatCTM(ctx, transform);
    switch (aImage.imageOrientation) {
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            // Grr...
            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.height,aImage.size.width), aImage.CGImage);
            break;
        default:
            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.width,aImage.size.height), aImage.CGImage);
            break;
    }
    // And now we just create a new UIImage from the drawing context
    CGImageRef cgimg = CGBitmapContextCreateImage(ctx);
    UIImage *img = [UIImage imageWithCGImage:cgimg];
    CGContextRelease(ctx);
    CGImageRelease(cgimg);
    return img;
}

//缩放图片
- (UIImage *)scaleImage:(UIImage *)image toScale:(float)scaleSize
{
    UIGraphicsBeginImageContext(CGSizeMake(image.size.width*scaleSize,image.size.height*scaleSize));
    [image drawInRect:CGRectMake(0, 0, image.size.width * scaleSize, image.size.height *scaleSize)];
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    //NSLog(@"%@",NSStringFromCGSize(scaledImage.size));
    return scaledImage;
}

//保存照片到沙盒路径(保存)
- (void)saveImage:(UIImage *)image name:(NSString *)iconName {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
    NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.png", iconName]];//保存路径
    //保存
    [UIImagePNGRepresentation(image)writeToFile:filePath  atomically:YES];
}
#pragma mark -------- Camera Utility --------
- (BOOL) isCameraAvailable{
    return [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
}

- (BOOL) isRearCameraAvailable{
    return [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear];
}

- (BOOL) isFrontCameraAvailable {
    return [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront];
}

- (BOOL) doesCameraSupportTakingPhotos {
    return [self cameraSupportsMedia:(__bridge NSString *)kUTTypeImage sourceType:UIImagePickerControllerSourceTypeCamera];
}

- (BOOL) isPhotoLibraryAvailable{
    return [UIImagePickerController isSourceTypeAvailable:
            UIImagePickerControllerSourceTypePhotoLibrary];
}
- (BOOL) canUserPickVideosFromPhotoLibrary{
    return [self
            cameraSupportsMedia:(__bridge NSString *)kUTTypeMovie sourceType:UIImagePickerControllerSourceTypePhotoLibrary];
}
- (BOOL) canUserPickPhotosFromPhotoLibrary{
    return [self
            cameraSupportsMedia:(__bridge NSString *)kUTTypeImage sourceType:UIImagePickerControllerSourceTypePhotoLibrary];
}

- (BOOL) cameraSupportsMedia:(NSString *)paramMediaType sourceType:(UIImagePickerControllerSourceType)paramSourceType{
    __block BOOL result = NO;
    if ([paramMediaType length] == 0) {
        return NO;
    }
    NSArray *availableMediaTypes = [UIImagePickerController availableMediaTypesForSourceType:paramSourceType];
    [availableMediaTypes enumerateObjectsUsingBlock: ^(id obj, NSUInteger idx, BOOL *stop) {
        NSString *mediaType = (NSString *)obj;
        if ([mediaType isEqualToString:paramMediaType]){
            result = YES;
            *stop= YES;
        }
    }];
    return result;
}


@end







